<template>
	<view class='body'>
		<!-- 抽屉 -->
		<uni-drawer ref="showRight" mode="left" :mask-click="true">
			<scroll-view style="height: 100%;" scroll-y="true">
				<view
					style="display: flex;flex-direction: column;align-items: center;margin:30rpx;padding-top: 100rpx;">
					<image src="../../static/logo.png" style="width: 150rpx;height: 150rpx;"></image>
					<text class="text-lg padding-tb-sm">宝宝成长记事本v2.0.1</text>
				</view>
				<view class="cu-list menu" :class="[menuBorder?'sm-border':'',menuCard?'card-menu margin-top':'']">


					<view class="cu-item item-height" :class="menuArrow?'arrow':''">
						<navigator class="content" hover-class="none" url='../babylist/babylist'>
							<text class="cuIcon-group text-orange"></text>
							<text class="text-grey">我的宝宝</text>
						</navigator>
					</view>

					<view class="cu-item" :class="menuArrow?'arrow':''">
						<navigator class="content" hover-class="none" url="../milklist/milklist">
							<text class="cuIcon-list text-orange"></text>
							<text class="text-grey">喂养记录</text>
						</navigator>
					</view>

					<view class="cu-item item-height" :class="menuArrow?'arrow':''">
						<navigator class="content" hover-class="none" url="../home/home">
							<text class="cuIcon-settings text-orange"></text>
							<text class="text-grey">个人设置</text>

						</navigator>
					</view>

					<view class="cu-item" :class="menuArrow?'arrow':''">
						<navigator class="content" hover-class="none" url="../aboutme/aboutme">
							<text class="cuIcon-warn text-green"></text>
							<text class="text-grey">关于本小程序</text>
						</navigator>
					</view>
				</view>

			</scroll-view>
		</uni-drawer>
		<!-- 抽屉结束 -->
		<view class="top">
			<view class="top-top" @click="showDrawer">
				<text class="top-top-head cuIcon-moreandroid text-xsl">菜单</text>
			</view>
			<view class="top-mid">

				<view class="top-mid-main">{{tscontent}}</view>

				<text v-if="tsdata.data" class="top-text-a">{{tsdata.data.babynike}} : {{age}}</text>
				<text v-else class="top-text-a">添加宝宝资料</text>

				<text class="top-text-b">{{tstime}} 第{{newcount}}次</text>
			</view>
			<view class="top-bottom">
			
			</view>
		</view>
		<view class="bottom">
			<!-- form表单 -->
			<view class="form">
				<view style="display: flex;flex-direction: row;">
					<view><input type="number" name="user_id" v-show="false" :value="String(user_id)" /></view>
					<view><input type="number" name="bb_id" v-show="false" :value="String(bb_id)" /></view>
				</view>

				<view class="cu-form-group" style="justify-content: center;">
					喂养数量
				</view>
				<picker-view class="picker-view" indicator-class="picker-indicator" :value="index" @change="bindChange">

					<picker-view-column class="picker-column">
						<view class="item" v-for="item,index in milks" :key="index">{{item}}ml</view>
					</picker-view-column>
				</picker-view>

				<button class="zbtn cu-btn bg-red margin-tb-sm lg" style="margin-top: 50rpx;"
					@click="addMilk">记录</button>

			</view>

		</view>

	</view>
</template>

<script>
	import url_config from '@/common/config.js'
	export default {
		data() {
			const milks = []
			for (let i = 10; i <= 300; i += 5) {
				milks.push(i)
			}
			return {
				newlist: [],
				BabyInfo: [],
				newcount: 0,
				//list: [],
				//lasttime: [],
				//用户登录后拉取user_id,bb_id
				user_id: 0,
				bb_id: 0,
				empty: false,
				signs: 0,
				age: '0岁1个月20天',
				milks,
				pmilk: 0,
				index: [1],
				menuBorder: true,
				menuArrow: true,
				menuCard: true,
				tsdata: [],
				tscontent: 0,
				tstime: ''
				//默认值下标为1，picker组件value的值是个数组
			}
		},

		methods: {
			showDrawer() {
				this.$refs.showRight.open();
			},
			hiddenDrawer() {
				this.$refs.showRight.close();
			},
			//添加记录
			addMilk() {
				let self = this;
				if (self.bb_id == 0) {
					//如果宝宝ID=0则需要添加宝宝

					uni.showModal({
						title: '提示信息',
						content: '请先添加一个宝宝信息',
						cancelText: "取消",
						confirmText: "确定",
						confirmColor: '#F2C827',
						cancelColor: '#9E9E9E',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '../babylist/addbaby/addbaby?uid=' + self.user_id
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					uni.request({
						url: url_config.api + 'addMilk',
						data: {
							user_id: self.user_id,
							content: self.pmilk,
							bb_id: self.bb_id
						},
						method: 'POST',
						success: (res) => {
							uni.showToast({
								title: '提交成功',
								duration: 2000 //持续时间
							});
							//添加成功之后刷新值
							//self.getList(self.user_id)
							self.getNum(self.bb_id)
							self.getMilk(self.bb_id)
						},
						complete(e) {
							//不管是否调用成功都会执行
							//console.log(e.data)
						}
					})
				}
			},
			editLog(id) {
				console.log(id)
				//跳转到编辑页面
				uni.redirectTo({
					url: '../edit/edit?id=' + id
				})
			},
			bbMilk(msg, id = 0) {
				uni.showToast({
					title: msg,
					duration: 2000
				});

			},
			setlocaldata(id) {
				//TODO 右侧按钮临时作为测试缓存变更
				console.log(id)
				try {
					uni.setStorageSync('user_id', id);
					uni.showToast({
						title: '设置本地缓存user_id:' + id,
						duration: 2000
					})
				} catch (e) {
					console.log(e)
				}
			},
			getNum(bid) {
				//获取指定BB当天喂养记录次数
				//console.log('getBBNum:bid:' + bid)
				if(bid==''){
					bid = 0
				}
				
				uni.request({
					url: url_config.api + 'getNum/' + bid,
					success: (res) => {
						//console.log(res.data.data)
						this.newcount = res.data.data
					},
					fail: (err) => {
						console.log('请求喂养次数失败')
					}
				})
			},
			getMilk(bid) {
				//获取宝宝信息以及该宝宝最近一次喂养记录
				//console.log('bid------------:', bid)
				if (bid=='') {
					bid = 0
					//console.log('bid------------:', bid)
					//宝宝记录为空的时候birthday给个默认值
				}
				uni.request({
					url: url_config.api + 'getMilk/' + bid,
					success: (res) => {
						//console.log('最近一次记录', res.data.code,bid)
						if (res.data.code == 200) {
							this.tsdata = res.data
							this.age = this.getBabyAge2(res.data.data.birthday)
							//console.log(res.data.data.Milk.length)
							if (res.data.data.Milk.length > 0) {
								this.tscontent = res.data.data.Milk[0].content
								this.tstime = res.data.data.Milk[0].create_time
							}
						}

					}
				})
			},
			setting() {
				uni.navigateTo({
					url: '../setting/setting?user_id=' + this.user_id
				})
			},
			gohome() {
				uni.navigateTo({
					url: '../home/home?user_id=' + this.user_id
				})
			},
			bindChange(e) {
				//picker-view组件，滑动选择喂养量，暂时不用，等主业务流程跑通再说2022-03-27
				const val = e.detail.value
				//获取value值，用来初始化picker选项
				//console.log('val：',JSON.stringify(val))
				this.pmilk = this.milks[val[0]]
				this.index = val
				try {
					//缓存当前选中的值为下次打开使用
					uni.setStorageSync('index', val)
					uni.setStorageSync('pmilk', this.milks[val[0]])
					//console.log('index值：',val[0])
				} catch (e) {
					//TODO handle the exception
				}

			},

			// 根据日期计算宝宝年龄
			getBabyAge2(datestring) {
				//注意：传入10位时间戳需要*1000，13位不需要，否则比较时间为1970
				var age;
				let nowTime = new Date();
				let birthTime = new Date(datestring);

				//console.log("time", nowTime, birthTime);
				// 当前年月日
				let curYear = nowTime.getFullYear();
				//console.log('现在:' + curYear)
				let curMonth = nowTime.getMonth();
				let curDay = nowTime.getDate();
				// 出生年月日
				let birYear = birthTime.getFullYear();
				//console.log(birYear);
				let birMonth = birthTime.getMonth();
				let birDay = birthTime.getDate();
				// 年月日之差
				let year = curYear - birYear;
				let months = curMonth - birMonth;
				let day = curDay - birDay;
				// console.log("test",year,months,day);
				//（1）将出生日期的时间戳都转化为Date，分别获取当前时间和出生时间的年、月、日之差
				//（2）若月份相差为负说明不满这一年，年份减1，月份借了一年变为12+当前月份。故月份之差变为12+当前月份-出生月份。
				// 若月份相差为0并且天相差为负，说明也不满一年，计算同理。
				//（3）若天相差为负，说明不满这个月，月份减1，天数借了一个月，故天数之差为上个月的天数+当前天-出生天
				if (months < 0 || months == 0 && day < 0) {
					year -= 1;
					months = 12 + curMonth - birMonth;
				}
				if (day < 0) {
					months -= 1;
					let date = this.getDaysInMonth(curYear, curMonth);
					//console.log("date",date);
					day = date + curDay - birDay;
				}
				age = year + '岁' + months + '个月' + day + '天';
				// console.log("age",age);
				return age;
			},
			// 获取某年某月有多少天
			getDaysInMonth(year, month) {
				month = parseInt(month, 10);
				var temp = new Date(year, month, '0');
				return temp.getDate();
			},

		},
		filters: {
			//过滤器 格式化时间 默认参数过滤数据，分隔符
			formatDate: function(value, spe = '/') {
				value = value * 1000 //小于10位则*1000
				let data = new Date(value);
				let year = data.getFullYear();
				let month = data.getMonth() + 1;
				let day = data.getDate();
				let h = data.getHours();
				let mm = data.getMinutes();
				let s = data.getSeconds();
				month = month >= 10 ? month : "0" + month;
				day = day >= 10 ? day : "0" + day;
				h = h >= 10 ? h : "0" + h;
				mm = mm >= 10 ? mm : "0" + mm;
				s = s >= 10 ? s : "0" + s;
				return `${year}${spe}${month}${spe}${day} ${h}:${mm}:${s}`;
			}
		},
		created() {
			//读取缓存获取user_id/openid
			try {

				//const openid = uni.getStorageSync('openid')
				const userId = uni.getStorageSync('user_id')
				const bbId = uni.getStorageSync('bb_id')
				//每次打开读取上次选择喂养数量
				const value2 = uni.getStorageSync('pmilk')
				if (userId) {
					//console.log('本地缓存用户ID：', userId)
					//console.log('本地缓存bb_id：' + bbId)
					this.user_id = userId
					this.bb_id = bbId

				} else {
					//非注册用户首次登录，自动注册
					uni.request({
						url: url_config.api + 'autoAddUser',
						method: 'POST',
						data: {
							nickName: '临时用户',
							avatarurl: url_config.pic + 'images/headicon/h1.png'
						},
						success: (res) => {
							//console.log('首次使用自动创建用户：', res.data.data)
							try {
								uni.setStorageSync('user_id', res.data.data)
								this.user_id = res.data.data
							} catch (e) {
								console.log(e)
							}
						}
					})
				}
				//缓存喂养量
				const localmilk = uni.getStorageSync('index')
				const localpmilk = uni.getStorageSync('pmilk')
				if (localmilk) {
					this.index = localmilk
					this.pmilk = localpmilk
				} else {
					console.log('缓存为空')
				}
			} catch (e) {

			}

			//获取记录列表
			//this.getbabylog(this.user_id, this.bb_id)
			//获取最近一次喂养记录
			//this.getbabylast(this.user_id, this.ischoose, this.bb_id)
			//初始化记录，bb_id为0
			//this.getList(this.user_id)
			//this.getBabyInfo(this.bb_id)
			this.getNum(this.bb_id)
			// this.getlist(this.user_id, this.bb_id, 1)
			//获取当前登录用户宝宝
			//this.getBaby(this.user_id)
			//环境标志
			this.signs = url_config.signtap
			//TODO 首次创建用户ID仅针对了本地没有查线上，授权过期？
			// 查询数据为空记录时到反馈。

		},
		onLoad() {
			//微信小程序分享功能
			uni.showShareMenu({
				//小程序原生菜单中显示分享按钮，才能够让发送给朋友与分享到朋友圈可点击
				menus: ["shareAppMessage", "shareTimeline"],
				//不设置默认发送给朋友
			})
		},
		onShareAppMessage(res) {
			//发送给朋友
			return {
				title: '宝宝喂养记录',
				path: '',
				imageUrl: '' //图片路径，支持本地或网络路径，图片尺寸5:4
			}
		},
		onShareTimeline(res) {
			//分享到朋友圈
			return {
				title: '宝宝喂养记录',
				query: '', //页面参数
				imageUrl: '' //图片路径
			}
		},
		onShow() {
			//切换宝宝默认状态后更新首页数据
			const userId = uni.getStorageSync('user_id')
			const bbId = uni.getStorageSync('bb_id')
			this.user_id = userId
			this.bb_id = bbId
			//获取宝宝及最近一次喂养记录
			this.getMilk(this.bb_id)
			//获取宝宝信息
			//this.getBabyInfo(this.bb_id)
			//获取当日次数
			this.getNum(this.bb_id)
			this.$nextTick(function() {
				//直接在onshow中调用hiddenDrawer这类控制DOM元素的方法时会报错
				//如此处会报为定义的close，因为是异步加载，会导致这类问题
				this.hiddenDrawer()
				//隐藏菜单

			})


		}
		//async onShow() {
		// 	//页面每次刷新时会调用，需要用异步调用才能获取到变量值
		// 	const bid = uni.getStorageSync('bb_id')
		// 	console.log('onshow', this.user_id)
		// 	console.log('bid:', bid)
		// 	await this.getBabyInfo(bid)
		// 	// this.getNum(this.bb_id)
		// }

	}
</script>

<style>
	.body {
		display: flex;
		flex-direction: column;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		/* z-index: -1; */
		background: #C6FFDD;
		/* fallback for old browsers */
		background: -webkit-linear-gradient(to top, #f7797d, #FBD786, #C6FFDD);
		/* Chrome 10-25, Safari 5.1-6 */
		background: linear-gradient(to top, #f7797d, #FBD786, #C6FFDD);
		/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
		align-items: center;

	}

	.top {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 50%;
		width: 100%;
	}

	.top-top {
		padding-top: 60rpx;
		padding-left: 25rpx;
		height: 20%;
		width: 90%;
	}

	.top-top-head {
		font-size: 33rpx;
		width: 80%;

	}

	.top-mid {
		height: 70%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #4c4c4c;

	}

	.top-mid-main {
		position: absolute;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 100px;
		border-radius: 50%;
		width: 450rpx;
		height: 450rpx;
		background-color: #ffffff;

	}

	.top-text-a {

		z-index: 2;
	}

	.top-text-b {

		z-index: 2;
		margin-top: 230rpx;
	}

	.top-bottom {}

	.bottom {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.form {
		width: 90%;
		align-items: center;
		justify-content: center;
		background-color: #FFFFFF;
		padding: 20rpx;
		border-radius: 10px;
		position: fixed;
		display: block;
		bottom: 50rpx;
	}

	.btn {
		width: 100%;
		position: absolute;
		bottom: 20rpx;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
	}

	.zbtn {
		width: 100%;
		height: 100rpx;
		border-radius: 50px;
		font-size: 45rpx;
		background-color: #F7797D;

	}

	/* picker选择器样式 */
	.picker-view {
		//选择器主体
		width: 100%;
		height: 180rpx;
		text-align: center;
		/* background-color: #76be9b; */
	}

	.picker-indicator {
		//选中部分样式
		height: 80rpx;
		z-index: 0;
		border-radius: 50rpx;
	}

	.item {
		//供选择的部分样式
		line-height: 80rpx;
		text-align: center;
		font-size: 22px;
		/* background-color: #07C160; */
	}
</style>
